
package com.hyst.config;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**
 * @Description:实现EnvironmentAware接口是为了获取Environment不报空指针
 * @Date：2017年8月9日 @author： DongY
 * @version ：1.0 1.[2017年8月9日]CreatBy：dy
 */
@Configuration
@PropertySource(value = { "classpath:db.properties" })
@MapperScan("com.hyst.repository")
public class DataSourceConfig implements EnvironmentAware {
	// private Logger logger = LogManager.getLogger(DataSourceConfig.class);

	private Environment env;
	@Value("${jdbc.driverClass}")
	private String name;

	@Bean(name = "dataSource", destroyMethod = "", initMethod = "")
	public DataSource dataSource() {
		// logger.error("加载数据源" + name);
		final DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
		dataSource.setUrl(env.getProperty("jdbc.url"));
		dataSource.setUsername(env.getProperty("jdbc.user"));
		dataSource.setPassword(env.getProperty("jdbc.password"));
		dataSource.setMaxActive(env.getProperty("maxActive", Integer.class));
		dataSource.setInitialSize(1);
		dataSource.setMaxWait(env.getProperty("maxWait", Integer.class));
		dataSource.setMinIdle(env.getProperty("minIdle", Integer.class));
		dataSource.setTestOnBorrow(env.getProperty("testOnBorrow", Boolean.class));
		dataSource.setTestOnReturn(env.getProperty("testOnReturn", Boolean.class));
		dataSource.setTestWhileIdle(env.getProperty("testWhileIdle", Boolean.class));
		// 超时是否回收
		dataSource.setRemoveAbandoned(true);
		// 超过2分钟回收连接
		dataSource.setRemoveAbandonedTimeout(1200);
		return dataSource;
	}

	/**
	 * @return name 返回类型：String
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param 参数类型
	 *            String,name 要设置的字段 name
	 */
	public void setName(final String name) {
		this.name = name;
	}

	@Override
	public void setEnvironment(final Environment environment) {
		env = environment;
	}

	/*----------------------------下面是mybatis的配置---------------------------- */
	@Bean
	public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
		final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource());
		sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
				.getResources("classpath:" + env.getProperty("mybatis.mapperLocation")));
		sessionFactoryBean.setTypeAliasesPackage(env.getProperty("mybatis.TypeAliasesPackage"));
		sessionFactoryBean.setConfiguration(configuration());
		final Interceptor[] plugins = new Interceptor[] { pageInterceptor() };
		sessionFactoryBean.setPlugins(plugins);
		return sessionFactoryBean;
	}

	@Bean
	public MapperScannerConfigurer scanner() {
		final MapperScannerConfigurer scanner = new MapperScannerConfigurer();
		scanner.setBasePackage("com.hyst.repository");
		return scanner;
	}

	@Bean
	public org.apache.ibatis.session.Configuration configuration() {
		final org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setLazyLoadingEnabled(true);
		configuration.setLogImpl(org.apache.ibatis.logging.log4j2.Log4j2Impl.class);
		configuration.setLogPrefix("LOG4J2");
		return configuration;
	}

	/*----------------------------mybatis分页插件配置------------------------------*/
	@Bean
	public PageInterceptor pageInterceptor() {
		// logger.info("分页插件装配完成！");
		final PageInterceptor interceptor = new PageInterceptor();
		final Properties properties = new Properties();
		properties.setProperty("helperDialect", "mysql");
		interceptor.setProperties(properties);
		return interceptor;
	}

	// @Bean
	// public MybatisInterceptor mybatisInterceptor() {
	// return new MybatisInterceptor();
	// }
}
